import {Component, EventEmitter, OnInit, Output} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {FetchService} from '../../../core/net/fetch.service';
import {NzMessageService, NzModalService} from 'ng-zorro-antd';
import {Router} from '@angular/router';
import {isToday, format, subDays} from 'date-fns';
import * as moment from 'moment';

@Component({
  selector: 'app-dispatch-record',
  templateUrl: './dispatch-record.component.html',
  styleUrls: ['./dispatch-record.component.scss']
})
export class DispatchRecordComponent implements OnInit {
  searchForm: FormGroup;
  manageId = JSON.parse(localStorage.userInfo).manageId;
  tableData = [];
  total: number;
  pageNum = 1;
  pageSize = 50;
  loading = true;
  form: FormGroup;
  modalTitle: string = '';
  modalShow: boolean = false;
  selectedDay;
  dayList = [];
  channelOptions = [];
  selectedValue;
  objId;
  flowId;
  submitContent = {
    applyContent: '', // 申请内容
    approveContent: '', // 审核内容
    executeContent: '' // 执行内容
  };
  statusMap = {
    '-1': '默认',
    '2': '待审核',
    '3': '待反馈'
  };

  canalMap = {};
  canalInfo = null;
  @Output() dispatchCount = new EventEmitter<any>();

  constructor(private fb: FormBuilder,
              private fetchService: FetchService,
              private router: Router,
              private message: NzMessageService,
              private modal: NzModalService
  ) {
    this.searchForm = this.fb.group({
      keyword: [null],
      rangePickerTime: [[]],
      fromMember: [null],
      toMember: [null]
    });

    this.form = this.fb.group({
      id: [null],
      changeDate: [null],
      content: [null],
      fromMember: [null],
      toMember: [null],
      advice: [null]
    });
  }

  ngOnInit(): void {
    this.getChannelOption();
    this.getDayList();
  }

  queryInfo(reset: boolean = false): void {
    if (reset) {
      this.pageNum = 1;
    }
    const param = {
      date: this.selectedDay,
      keyword: this.searchForm.value.keyword,
      orderByField: 'ctTime',
      orderBy: 'desc'
    };
    this.fetchService.post<any>('schedule/wrsActualDispatchApplyNew/queryByDate', param).subscribe(res => {
      this.tableData = res;
      let num = 0;
      res.map(item => {
        if (item.step == 2 || item.step == 3) {
          num++;
        }
      });
      this.dispatchCount.emit(num);
    });
  }

  getChannelOption(): void {
    this.fetchService.post<any>('sys/sysApiInfo/queryApiData', {apicode: '13'})
      .subscribe(res => {
        if (res.length > 0) {
          this.channelOptions = res.map(item => {
            this.canalMap[item.objId] = item.name;
            return {
              name: item.name,
              value: `${item.flowId}|${item.objId}`,
              objType: item['obj_type']
            };
          });
          this.selectedValue = this.channelOptions[0].value;
          this.channelSelectChange();
        }
      });
  }

  channelSelectChange(): void {
    const params: any = {
      objId: this.selectedValue.split('|')[1],
      objType: this.channelOptions.find(item => {
        return item.value === this.selectedValue;
      })['objType']
    };
    this.fetchService.post<any>('schedule/wrsActualDispatchApplyNew/obj', params).subscribe(res => {
      this.canalInfo = res;
      this.canalInfo['name'] = this.channelOptions.find(item => {
        return item.value === this.selectedValue;
      })['name'];
    });
  }

  // 发起申请流程
  onApply(): void {
    this.modal.confirm({
      nzTitle: '确认加减水申请？',
      nzContent: '',
      nzOnOk: () => {
        const formData: any = {
          objId: this.selectedValue.split('|')[1],
          applyContent: this.submitContent['applyContent'],
          objType: this.channelOptions.find(item => {
            return item.value === this.selectedValue;
          })['objType']
        };
        const param = {
          flowId: this.selectedValue.split('|')[0],
          formData: JSON.stringify(formData)
        };
        this.fetchService.post('flow/flowInst/submit', param).subscribe(res => {
          this.message.success('操作成功！');
          this.modalShow = false;
          this.getDayList();
        });
      }
    });
  }

  // 发起审核或者执行流程
  onAudit(contentName, form): void {
    const formData: any = {};
    formData[contentName] = form[contentName];

    const param = {
      instId: form.instId,
      formData: JSON.stringify(formData)
    };
    this.fetchService.post('flow/flowInst/audit', param).subscribe(res => {
      this.message.success('操作成功！');
      this.queryInfo();
    });

  }

  // 选择右侧日期
  selectDay(data): void {
    this.selectedDay = data.value;
    this.queryInfo();
  }

  onAdd(): void {
    this.modalTitle = '新增调度日志';
    this.form.reset();
    this.modalShow = true;
    // 清空内容
    this.submitContent = {
      applyContent: '',
      approveContent: '',
      executeContent: ''
    };
  }

  onCancel() {
    this.modalShow = false;
  }

  getDayList(): void {
    const stDate = this.searchForm.value.rangePickerTime[0] ? format(this.searchForm.value.rangePickerTime[0], 'YYYY-MM-DD') : '';
    const edDate = this.searchForm.value.rangePickerTime[1] ? format(this.searchForm.value.rangePickerTime[1], 'YYYY-MM-DD') : '';
    const param = {
      stDate: stDate,
      edDate: edDate,
      keyword: this.searchForm.value.keyword,
      orderByField: 'ctTime',
      orderBy: 'desc',
      pageSize: 10000
    };
    this.fetchService.post<any>('schedule/wrsActualDispatchApplyNew/queryDate', param).subscribe(res => {
      this.dayList = res.list.map(item => {
        return {
          text: format(item.date, 'MM月DD日'),
          value: item.date
        };
      });
      this.selectDay(this.dayList[0]);
    });
  }

  exportDocx(): void {
    const stDate = this.searchForm.value.rangePickerTime[0] ? format(this.searchForm.value.rangePickerTime[0], 'YYYY-MM-DD') : '';
    const edDate = this.searchForm.value.rangePickerTime[1] ? format(this.searchForm.value.rangePickerTime[1], 'YYYY-MM-DD') : '';
    const params = {
      stDate: stDate,
      edDate: edDate,
      userId: JSON.parse(localStorage.userInfo).id,
      manageId: JSON.parse(localStorage.userInfo).manageId,
    };
    this.fetchService.export(`comm/word/exportWord`, {
      wordMapper: "WordMapper-wrsActualDispatchApplyNew",
      queryParams: JSON.stringify(params),
      targetFileName: "加减水记录.docx"
    }).subscribe(data => {
      const fileBlob = new Blob([data], {type: 'charset=utf-8'});
      const link = document.createElement('a');
      link.id = 'waterRecodeDownloadId';
      document.body.appendChild(link);
      link.style.display = 'none';
      link.download = "加减水记录.docx";
      link.href = URL.createObjectURL(fileBlob);
      link.click();
      const tempA = document.getElementById('waterRecodeDownloadId');
      if (tempA) {
        tempA.parentNode.removeChild(tempA);
      }
    });
  }
}
